import React, { Fragment } from 'react';
import { Form, Input, Button } from 'antd';
import { useHistory } from 'react-router-dom';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import styles from './style.module.scss'

import { login } from '../../api';
import { TOKEN } from '../../constan';

export default function Login() {
  const history = useHistory()
  const [form] = Form.useForm();


  const onFinish = async (values) => {

    const res = await login(values)
    if (res) {

      localStorage.setItem(TOKEN, JSON.stringify(res))
      history.push('/')
    }
  };
  return (
    <div className={styles.login}>
      <div className={styles.loginBox}>
        <Form form={form} name="horizontal_login" layout="inline" onFinish={onFinish}>
          <Form.Item
            name="username"
            style={{ width: '100%', marginTop: '100px' }}
            rules={[{ required: true, message: 'Please input your username!' }]}
          >
            <Input size='large' prefix={<UserOutlined className="site-form-item-icon" />} placeholder="Username" />
          </Form.Item>
          <Form.Item
            name="password"
            style={{ width: '100%', marginTop: '15px' }}
            rules={[{ required: true, message: 'Please input your password!' }]}
          >
            <Input
              size='large'
              prefix={<LockOutlined className="site-form-item-icon" />}
              type="password"
              placeholder="Password"
            />
          </Form.Item>
          <Form.Item shouldUpdate className={styles.btnGroup}>
            {() => (
              <Fragment >

                <Button style={{ marginLeft: '10px', float: 'right' }} size='large' type='primary' onClick={() => {
                  form.resetFields()

                }}  >重置</Button>
                <Button
                  type="primary"
                  htmlType="submit"
                  style={{ float: 'right' }}
                  disabled={
                    !form.isFieldsTouched(true) ||
                    !!form.getFieldsError().filter(({ errors }) => errors.length).length
                  }
                  size='large'
                >
                  登陆
                </Button>
              </Fragment>
            )}
          </Form.Item >

        </Form>
      </div>
    </div>

  )
}
